<template>
  <div class="inventory-overview">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>库存概览</h3>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData">
              <el-icon><RefreshRight /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 库存统计卡片 -->
      <div class="stat-cards">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="商品总数">
            <template #value>
              <div class="statistic-content">
                <el-icon class="stat-icon"><Goods /></el-icon>
                <span class="stat-value">{{ totalProducts }}</span>
              </div>
            </template>
          </el-statistic>
        </el-card>
        
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="预警商品">
            <template #value>
              <div class="statistic-content">
                <el-icon class="stat-icon warning"><WarningFilled /></el-icon>
                <span class="stat-value warning">{{ warningProducts }}</span>
              </div>
            </template>
          </el-statistic>
        </el-card>
        
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="缺货商品">
            <template #value>
              <div class="statistic-content">
                <el-icon class="stat-icon danger"><CircleCloseFilled /></el-icon>
                <span class="stat-value danger">{{ outOfStockProducts }}</span>
              </div>
            </template>
          </el-statistic>
        </el-card>
      </div>
      
      <!-- 搜索和筛选 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品"
          class="search-input"
          clearable
          @clear="handleSearch"
          @input="handleSearchInput"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
        
        <el-select v-model="filterStatus" placeholder="库存状态" @change="handleFilterChange" clearable>
          <el-option label="全部" value="" />
          <el-option label="正常" value="normal" />
          <el-option label="预警" value="warning" />
          <el-option label="缺货" value="out_of_stock" />
        </el-select>
        
        <el-select v-model="filterCategory" placeholder="商品分类" @change="handleFilterChange" clearable>
          <el-option label="全部" value="" />
          <el-option
            v-for="category in categoryOptions"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </div>
      
      <!-- 库存列表 -->
      <el-table
        :data="filteredProducts"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column label="商品信息" min-width="200" class-name="text-left">
          <template #default="scope">
            <div class="product-info">
              <el-image
                :src="scope.row.imageUrl || '/images/products/default.png'"
                fit="cover"
                class="product-image"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="product-details">
                <div class="product-name">{{ scope.row.name }}</div>
                <div class="product-category">{{ getCategoryName(scope.row.categoryId) }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="stockQuantity" label="库存数量" width="120" sortable>
          <template #default="scope">
            {{ scope.row.stockQuantity || 0 }} {{ scope.row.stockUnit || '个' }}
          </template>
        </el-table-column>
        <el-table-column prop="minimumStock" label="最低库存" width="120">
          <template #default="scope">
            {{ scope.row.minimumStock || '-' }} {{ scope.row.stockUnit || '个' }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="售价" width="100" sortable>
          <template #default="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="costPrice" label="成本价" width="100" sortable>
          <template #default="scope">
            ¥{{ scope.row.costPrice ? scope.row.costPrice.toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="stockStatus" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row)">
              {{ getStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleViewDetails(scope.row)"
            >
              详情
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleAdjustInventory(scope.row)"
              :disabled="!hasAdjustPermission"
            >
              调整
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 库存调整弹窗 -->
    <el-dialog
      v-model="adjustDialogVisible"
      title="库存调整"
      width="500px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedProduct" class="adjust-dialog-content">
        <div class="product-info-dialog">
          <div class="product-name">{{ selectedProduct.name }}</div>
          <div class="product-stock">
            当前库存: {{ selectedProduct.stockQuantity || 0 }} {{ selectedProduct.stockUnit || '个' }}
          </div>
        </div>
        
        <el-form ref="adjustFormRef" :model="adjustForm" :rules="adjustRules" label-width="100px">
          <el-form-item label="仓库" prop="warehouseId">
            <el-select v-model="adjustForm.warehouseId" placeholder="选择仓库" style="width: 100%">
              <el-option
                v-for="warehouse in warehouses"
                :key="warehouse.id"
                :label="warehouse.name"
                :value="warehouse.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="调整类型" prop="adjustmentType">
            <el-select v-model="adjustForm.adjustmentType" placeholder="选择调整类型" style="width: 100%">
              <el-option :label="'入库调整'" :value="1" />
              <el-option :label="'出库调整'" :value="2" />
              <el-option :label="'损坏出库'" :value="3" />
              <el-option :label="'过期出库'" :value="4" />
              <el-option :label="'其他调整'" :value="5" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="调整数量" prop="adjustmentQuantity">
            <el-input-number
              v-model="adjustForm.adjustmentQuantity"
              :precision="2"
              :step="1"
              :min="adjustmentMinValue"
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="adjustForm.remarks"
              type="textarea"
              :rows="3"
              placeholder="请输入调整原因或备注"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adjustDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdjustment" :loading="adjustSubmitting">
            确认调整
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  RefreshRight, 
  Goods, 
  WarningFilled, 
  CircleCloseFilled,
  Search,
  Picture
} from '@element-plus/icons-vue'
import { getInventoryOverview, getAllWarehouses, adjustInventory } from '@/api/inventory'

const router = useRouter()

// 页面数据
const loading = ref(false)
const products = ref([])
const totalProducts = ref(0)
const warningProducts = ref(0)
const outOfStockProducts = ref(0)
const warehouses = ref([])
const categoryOptions = ref([])

// 分页相关
const pageSize = ref(10)
const currentPage = ref(1)
const totalItems = computed(() => filteredProducts.value.length)

// 搜索和筛选
const searchKeyword = ref('')
const filterStatus = ref('')
const filterCategory = ref('')
const sortBy = ref('')
const sortOrder = ref('')

// 权限判断
const hasAdjustPermission = ref(true) // 实际项目中应该根据用户权限判断

// 计算过滤后的商品列表
const filteredProducts = computed(() => {
  let result = [...products.value]
  
  // 搜索关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item => 
      item.name.toLowerCase().includes(keyword) || 
      (item.description && item.description.toLowerCase().includes(keyword))
    )
  }
  
  // 状态过滤
  if (filterStatus.value) {
    if (filterStatus.value === 'warning') {
      result = result.filter(item => 
        item.stockStatus === 'warning' || 
        (item.minimumStock && item.stockQuantity < item.minimumStock)
      )
    } else if (filterStatus.value === 'out_of_stock') {
      result = result.filter(item => 
        item.stockStatus === 'out_of_stock' || 
        item.stockQuantity === 0 || 
        item.stockQuantity === null
      )
    } else {
      result = result.filter(item => item.stockStatus === filterStatus.value)
    }
  }
  
  // 分类过滤
  if (filterCategory.value) {
    result = result.filter(item => item.categoryId === filterCategory.value)
  }
  
  // 排序
  if (sortBy.value) {
    result.sort((a, b) => {
      const valueA = a[sortBy.value] !== null && a[sortBy.value] !== undefined ? a[sortBy.value] : 0
      const valueB = b[sortBy.value] !== null && b[sortBy.value] !== undefined ? b[sortBy.value] : 0
      
      if (sortOrder.value === 'ascending') {
        return valueA > valueB ? 1 : -1
      } else {
        return valueA < valueB ? 1 : -1
      }
    })
  }
  
  return result
})

// 获取当前页面的商品
const displayedProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredProducts.value.slice(start, end)
})

// 获取分类名称
const getCategoryName = (categoryId) => {
  const category = categoryOptions.value.find(item => item.id === categoryId)
  return category ? category.name : '-'
}

// 获取状态类型
const getStatusType = (product) => {
  if (product.stockStatus === 'out_of_stock' || product.stockQuantity === 0 || product.stockQuantity === null) {
    return 'danger'
  } else if (product.stockStatus === 'warning' || (product.minimumStock && product.stockQuantity < product.minimumStock)) {
    return 'warning'
  } else {
    return 'success'
  }
}

// 获取状态文本
const getStatusText = (product) => {
  if (product.stockStatus === 'out_of_stock' || product.stockQuantity === 0 || product.stockQuantity === null) {
    return '缺货'
  } else if (product.stockStatus === 'warning' || (product.minimumStock && product.stockQuantity < product.minimumStock)) {
    return '预警'
  } else {
    return '正常'
  }
}

// 搜索和筛选处理
const handleSearch = () => {
  currentPage.value = 1
}

const handleSearchInput = (value) => {
  if (!value) {
    handleSearch()
  }
}

const handleFilterChange = () => {
  currentPage.value = 1
}

const handleSortChange = ({ prop, order }) => {
  sortBy.value = prop
  sortOrder.value = order
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 查看商品详情
const handleViewDetails = (product) => {
  router.push(`/admin/inventory/product/${product.id}`)
}

// 库存调整相关
const adjustDialogVisible = ref(false)
const adjustSubmitting = ref(false)
const selectedProduct = ref(null)
const adjustForm = reactive({
  productId: null,
  warehouseId: null,
  adjustmentType: 1,
  adjustmentQuantity: 1,
  remarks: ''
})

const adjustRules = {
  warehouseId: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ],
  adjustmentType: [
    { required: true, message: '请选择调整类型', trigger: 'change' }
  ],
  adjustmentQuantity: [
    { required: true, message: '请输入调整数量', trigger: 'blur' }
  ]
}

// 计算调整数量的最小值
const adjustmentMinValue = computed(() => {
  // 出库类型调整，限制不能超过当前库存
  if (adjustForm.adjustmentType > 1 && selectedProduct.value) {
    return -selectedProduct.value.stockQuantity || -9999
  }
  return -9999 // 入库不限制
})

// 调整库存
const handleAdjustInventory = (product) => {
  selectedProduct.value = product
  adjustForm.productId = product.id
  adjustForm.warehouseId = warehouses.value.length > 0 ? warehouses.value[0].id : null
  adjustForm.adjustmentType = 1
  adjustForm.adjustmentQuantity = 1
  adjustForm.remarks = ''
  adjustDialogVisible.value = true
}

// 提交库存调整
const adjustFormRef = ref(null)
const submitAdjustment = async () => {
  if (!adjustFormRef.value) return
  
  await adjustFormRef.value.validate(async (valid) => {
    if (valid) {
      adjustSubmitting.value = true
      
      try {
        // 调整库存
        const response = await adjustInventory({
          productId: adjustForm.productId,
          warehouseId: adjustForm.warehouseId,
          adjustmentType: adjustForm.adjustmentType,
          // 如果是出库类型(2-5)且数量为正数，则转为负数
          adjustmentQuantity: adjustForm.adjustmentType > 1 && adjustForm.adjustmentQuantity > 0 
            ? -adjustForm.adjustmentQuantity 
            : adjustForm.adjustmentQuantity,
          remarks: adjustForm.remarks
        })
        
        if (response.success) {
          ElMessage.success('库存调整成功')
          adjustDialogVisible.value = false
          refreshData() // 刷新数据
        } else {
          ElMessage.error(response.message || '库存调整失败')
        }
      } catch (error) {
        console.error('库存调整失败:', error)
        ElMessage.error('库存调整失败')
      } finally {
        adjustSubmitting.value = false
      }
    }
  })
}

// 刷新数据
const refreshData = async () => {
  loading.value = true
  try {
    // 获取库存概览数据
    const response = await getInventoryOverview()
    
    if (response.success) {
      products.value = response.data.products || []
      totalProducts.value = response.data.totalProducts || 0
      warningProducts.value = response.data.warningProducts || 0
      outOfStockProducts.value = response.data.outOfStockProducts || 0
      
      // 提取分类选项
      const categories = new Map()
      products.value.forEach(product => {
        if (product.category && !categories.has(product.category.id)) {
          categories.set(product.category.id, {
            id: product.category.id,
            name: product.category.name
          })
        }
      })
      categoryOptions.value = Array.from(categories.values())
    } else {
      ElMessage.error(response.message || '获取库存数据失败')
    }
    
    // 获取仓库列表
    const warehouseResponse = await getAllWarehouses()
    if (warehouseResponse.success) {
      warehouses.value = warehouseResponse.data || []
    }
  } catch (error) {
    console.error('获取库存数据失败:', error)
    ElMessage.error('获取库存数据失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.inventory-overview {
  padding-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.statistic-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.stat-icon {
  font-size: 24px;
  color: #409EFF;
}

.stat-icon.warning {
  color: #E6A23C;
}

.stat-icon.danger {
  color: #F56C6C;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.stat-value.warning {
  color: #E6A23C;
}

.stat-value.danger {
  color: #F56C6C;
}

.search-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.product-details {
  display: flex;
  flex-direction: column;
}

.product-name {
  font-weight: bold;
}

.product-category {
  font-size: 12px;
  color: #909399;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
}

.product-info-dialog {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #EBEEF5;
}

.product-info-dialog .product-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.product-info-dialog .product-stock {
  font-size: 14px;
  color: #606266;
}
</style> 